#!/usr/bin/env python3

# Copyright (c) 2020-2025 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import re
import pathlib
from .._errors import InvalidMainTargetError
from ._target import Target


class MainTarget(Target):

    # we don't adhere to systemd's native classification scheme, which is confusing
    #
    # main target must be user-aware, user should be able to isolate a main target
    # only some of the systemd build-in targets are our "main target", for custom main target, there must be flags in its config file
    #

    @classmethod
    def _create(cls, parent, dir_path, **kwargs):
        unitName = kwargs["name"] + ".target"
        fullfn = os.path.join(dir_path, unitName)
        pathlib.Path(fullfn).write_text(cls._generateMainTargetFileContent(kwargs["name"], kwargs["description"]))
        return cls(parent, unit_name=unitName)

    @classmethod
    def _exists(cls, parent, dir_path, **kwargs):
        unitName = kwargs["name"] + ".target"
        fullfn = os.path.join(dir_path, unitName)
        if not os.path.exists(fullfn):
            return None
        if pathlib.Path(fullfn).read_text() != cls._generateMainTargetFileContent(kwargs["name"], kwargs["description"]):
            return None
        return cls(parent, unit_name=unitName)

    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        if self._unitName not in _buildInMainTargets:
            if re.search("^# Main target$", self.unit_file_content, re.M) is None:
                raise InvalidMainTargetError(self.unit_file_path)

    def is_default(self):
        pass

    def set_as_default(self):
        pass

    def remove_and_dispose(self):
        assert not self.is_default()
        super().remove_and_dispose()

    @staticmethod
    def _generateMainTargetFileContent(name, description):
        buf = ""
        buf += "# Main target\n"
        buf += "[Unit]\n"
        buf += "Description=%s\n" % (description)
        return buf


_buildInMainTargets = [
    "multi-user.target",
    "graphical.target",
] + [
    "rescue.target",
    "emergency.target",
] + [
    "kexec.target",
    "reboot.target",
    "shutdown.target",
    "poweroff.target",
] + [
    "suspend.target",
    "hibernate.target",
    "suspend-then-hibernate.target",
]

# FIXME
# "halt.target",
# "hybrid-sleep.target",
# "idle.target",
# "suspend-then-idle.target",
